package Visao;

import Fachada.Fachada;
import Modelo.Hospede;
import Modelo.Hotel;
import Modelo.Quarto;
import Modelo.Reserva;
import RMI.ServicosCliente;
import RMI.ServicosIF;
import Util.Utils;
import java.rmi.RemoteException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;

/**
 *
 * @author Kassio Kiarelly Soares de Oliveira <kassiokiarelly@gmail.com>
 * @author Pablo Veinberg <pveinberg@gmail.com> 
 * 
 */
public class FormReserva extends javax.swing.JDialog {

    private Fachada fachada = Fachada.getInstance();
    private Reserva reserva = new Reserva();
    private boolean editing;
    private SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");

    public FormReserva() {
        init();
    }

    public FormReserva(Reserva r) {
        init();
        reserva = r;
        editing = true;      
    }

    private void init() {
        initComponents();
        setLocationRelativeTo(null);
    }

    public boolean isEditing() {
        return editing;
    }

    public Reserva getReserva() {
        return reserva;
    }

    public void setReserva(Reserva reserva) {
        this.reserva = reserva;
    }

    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jLabel1 = new javax.swing.JLabel();
        cmbHospede = new javax.swing.JComboBox();
        jLabel2 = new javax.swing.JLabel();
        cmbHotel = new javax.swing.JComboBox();
        jLabel3 = new javax.swing.JLabel();
        cmbQuarto = new javax.swing.JComboBox();
        jLabel4 = new javax.swing.JLabel();
        jLabel5 = new javax.swing.JLabel();
        dataInicio = new javax.swing.JFormattedTextField();
        dataFim = new javax.swing.JFormattedTextField();
        btSalvar = new javax.swing.JButton();

        setTitle("Reserva de quarto");
        setModal(true);
        setResizable(false);
        addWindowListener(new java.awt.event.WindowAdapter() {
            public void windowOpened(java.awt.event.WindowEvent evt) {
                formWindowOpened(evt);
            }
        });

        jLabel1.setText("Hospede");

        jLabel2.setText("Hotel");

        cmbHotel.addItemListener(new java.awt.event.ItemListener() {
            public void itemStateChanged(java.awt.event.ItemEvent evt) {
                cmbHotelItemStateChanged(evt);
            }
        });

        jLabel3.setText("Quarto");

        jLabel4.setText("Início");

        jLabel5.setText("Fim");

        dataInicio.setFormatterFactory(new javax.swing.text.DefaultFormatterFactory(new javax.swing.text.DateFormatter()));

        dataFim.setFormatterFactory(new javax.swing.text.DefaultFormatterFactory(new javax.swing.text.DateFormatter()));

        btSalvar.setText("Salvar");
        btSalvar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btSalvarActionPerformed(evt);
            }
        });

        org.jdesktop.layout.GroupLayout layout = new org.jdesktop.layout.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(layout.createSequentialGroup()
                .addContainerGap()
                .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.TRAILING)
                    .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                        .add(jLabel1)
                        .add(org.jdesktop.layout.GroupLayout.TRAILING, jLabel2)
                        .add(layout.createSequentialGroup()
                            .add(20, 20, 20)
                            .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.TRAILING)
                                .add(jLabel4)
                                .add(jLabel5))))
                    .add(jLabel3))
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                    .add(layout.createSequentialGroup()
                        .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING, false)
                            .add(dataInicio, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 116, Short.MAX_VALUE)
                            .add(dataFim)
                            .add(cmbHotel, 0, 140, Short.MAX_VALUE)
                            .add(cmbQuarto, 0, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .add(cmbHospede, 0, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                        .add(0, 213, Short.MAX_VALUE))
                    .add(layout.createSequentialGroup()
                        .add(0, 272, Short.MAX_VALUE)
                        .add(btSalvar)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(layout.createSequentialGroup()
                .add(42, 42, 42)
                .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                    .add(jLabel1)
                    .add(cmbHospede, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                    .add(jLabel2)
                    .add(cmbHotel, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                    .add(jLabel3)
                    .add(cmbQuarto, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
                .add(18, 18, 18)
                .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                    .add(jLabel4)
                    .add(dataInicio, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                    .add(jLabel5)
                    .add(dataFim, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED, 55, Short.MAX_VALUE)
                .add(btSalvar)
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void formWindowOpened(java.awt.event.WindowEvent evt) {
        cmbHospede.removeAllItems();
        for (Hospede h : this.fachada.getDaoHospede().findAll()) {
            cmbHospede.addItem(h);
        }

        cmbHotel.removeAllItems();
        for (Hotel hotel : this.fachada.getDaoHotel().findAll()) {
            cmbHotel.addItem(hotel);
        }

        if (editing) atualizarOsCampos();  

    }

    private void atualizarOsCampos() {
        dataInicio.setText(sdf.format(this.getReserva().getInicio()));
        dataFim.setText(sdf.format(this.getReserva().getFim()));        
        cmbHospede.setSelectedItem(this.reserva.getHospede()); 
        cmbHotel.setSelectedItem(this.reserva.getHotel());
        cmbQuarto.setSelectedItem(this.reserva.getQuarto());
    }

    private void pegarValoresDosCampos() {
        Hospede hospede = (Hospede) cmbHospede.getSelectedItem();
        Hotel hotel = (Hotel) cmbHotel.getSelectedItem();
        Quarto quarto = (Quarto) cmbQuarto.getSelectedItem();

        Date inicio = new Date();
        Date fim = new Date();
        try {
            inicio = sdf.parse(dataInicio.getText());
            fim = sdf.parse(dataFim.getText());

        } catch (ParseException ex) {
            Logger.getLogger(FormReserva.class.getName()).log(Level.SEVERE, null, ex);
        }

        double saldo = Utils.GetDiasDeHospedagem(inicio, fim) * quarto.getDiaria();
        
        this.reserva.setHospede(hospede);
        this.reserva.setHotel(hotel);
        this.reserva.setQuarto(quarto);
        this.reserva.setInicio(inicio);
        this.reserva.setFim(fim);
        this.reserva.setTotalHospedagem(saldo);
    }

    private void btSalvarActionPerformed(java.awt.event.ActionEvent evt) {
//GEN-FIRST:event_btSalvarActionPerformed

        try {
            ServicosIF sc = ServicosCliente.getInstance();

            
            if (!isEditing()) {
                // novo
                this.pegarValoresDosCampos();
                int result = sc.addReserva(getReserva());
                switch (result) {
                    case Utils.USUARIO_SEM_SALDO:
                        JOptionPane.showMessageDialog(null, "Hóspede com pendências.");
                        init();
                    case Utils.QUARTO_OCUPADO:
                        JOptionPane.showMessageDialog(null, "Não foi psível adicionar sua reserva. Verifique se as datas estão disponíveis.");
                        break;
                    default:
                        JOptionPane.showMessageDialog(null, "A reserva foi adicionada com sucesso.");
                        break;
                }
                init();
                setVisible(false);
            } else {
                // edit
                this.pegarValoresDosCampos();
                int result = sc.editReserva(getReserva());
                switch (result) {
                    case Utils.QUARTO_OCUPADO:
                        JOptionPane.showMessageDialog(null, "Não foi psível atualizar a reserva. Verifique se as datas estão disponíveis.");
                        break;
                    default:
                        JOptionPane.showMessageDialog(null, "A reserva foi atualizada com sucesso.");
                        break;
                }
            }
            
            
            this.setVisible(false);
            init();
        } catch (RemoteException re) {
            JOptionPane.showMessageDialog(null, "Problemas de conexão com servidor.");
            this.setVisible(false);
            init();
        } catch (Exception e) {
            JOptionPane.showMessageDialog(null, "Problema finalizando a reserva. " + e.getMessage());
            this.setVisible(false);
            init();
        }
    }

//GEN-LAST:event_btSalvarActionPerformed

    private void cmbHotelItemStateChanged(java.awt.event.ItemEvent evt) {//GEN-FIRST:event_cmbHotelItemStateChanged
        Hotel hotel = (Hotel) cmbHotel.getSelectedItem();
        cmbQuarto.removeAllItems();
        for (Quarto quarto : hotel.getQuartos()) {
            cmbQuarto.addItem(quarto);
        }
    }//GEN-LAST:event_cmbHotelItemStateChanged
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btSalvar;
    private javax.swing.JComboBox cmbHospede;
    private javax.swing.JComboBox cmbHotel;
    private javax.swing.JComboBox cmbQuarto;
    private javax.swing.JFormattedTextField dataFim;
    private javax.swing.JFormattedTextField dataInicio;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    // End of variables declaration//GEN-END:variables
}
